<template lang="pug">
  div.kalix-header
    div.s-flex.bd
      div.logo
        <!--img(src="/static/images/logo_oa_horizontal.png")-->
        <!--span.tit 吉 林 省 行 氏 动 漫 科 技 有 限 公 司-->
        span.sub-tit 后 台 管 理 系 统
      div.s-flex_item
      div.s-flex.btn-area
        div.item 用户名： {{$store.state.currentUser.name}}
        div.item.lnk(v-if="isShowMessage" v-on:click="onMsgClick")
          i.xing-icon.xing-icon-message
          | 消息
        div.item.lnk
          i.xing-icon.xing-icon-toggle
          | 切换皮肤
        div.item.lnk(v-on:click="doLogout")
          i.xing-icon.xing-icon-out
          | 退出系统
</template>

<script type="text/ecmascript-6">
  export default {
    name: 'KalixHeader',
    data() {
      return {
        menuChk: false,
        isReceiveMsg: false, // 是否进行消息接收
        userName: '',
        menuList: [],
        singleLogin: true,
        headerMenuChk: this.menuChk,
        themeValue: '',
        msgCount: 0,
        menuIsOpen: false,
        isShowAsideBtn: false,
        isShowMessage: false,
        isFlowCommand: false
      }
    },
    props: {
      reqUrl: {
        type: String,
        default: ''
      },
      params: {
        type: Object,
        default() {
          return {
            _dc: (new Date()).getTime(),
            page: 1,
            start: 0,
            limit: 25
          }
        }
      },
      loginUrl: {
        type: String,
        default: ''
      },
      logoutUrl: {
        type: String,
        default: ''
      }
    },
    mounted() {
      console.log('KalixHeader mounted')
      this._setTopBtns()
    },
    activated() {
    },
    methods: {
      onMsgClick() {
        this.$router.push({path: `/common/receiver`})
      },
      doLogout() {
        this.msgCount = 0
        this.$http.get(this.logoutUrl, {})
          .then(response => {
            console.log('Logout:', response)
            if (this.isReceiveMsg && typeof (this.over) === 'function') {
              this.over()
            }
            this.$KalixCatch.clear()
            this.$KalixCatch._clearLocal()
            this.$router.push({path: this.loginUrl})
          })
          .catch(err => {
            console.log(' ===== err ===== ', err)
            if (this.isReceiveMsg && typeof (this.over) === 'function') {
              this.over()
            }
            this.$KalixCatch.clear()
            this.$KalixCatch._clearLocal()
            this.$router.push({path: this.loginUrl})
          })
      },
      handleCommand(command) {
        switch (command) {
          case 'changeInfo' :
            this.$emit('onClickUpdateUserInfo')
            break
          case 'changePwd':
            this.$emit('onClickChangePwd', '')
            break
          case 'logout' :
            this.doLogout()
            break
        }
      },
      // 使用websocket，用于客户端与服务器消息的传递
      websocket() {
        if ('WebSocket' in window) {
          let socketUrl = this.$KalixGlobalConfig.baseWsURL + '?loginname=' + this.$KalixCatch.get('loginname') + '&wsMessage=CommonMessage'
          let ws = new WebSocket(socketUrl)
          ws.onopen = () => {
            // Web Socket 已连接上，使用 send() 方法发送数据
          }
          ws.onmessage = evt => {
            //  获取消息数量
            let data = JSON.parse(evt.data)
            if (data && data.msgCount) {
              this.msgCount = data.msgCount
            } else {
              this.msgCount = 0
            }
            //  获取最新消息
            if (data && data.msgTag && data.msgTag.length) {
              let msg = JSON.parse(data.msgTag)
              let headerNotif = this.$notify({
                title: msg.title,
                message: msg.content,
                type: 'success',
                duration: 10000,
                onClick: () => {
                  this.$router.push({path: `/common/receiver`})
                  headerNotif.close()
                }
              })
            }
          }
          ws.onclose = function () {
            // 关闭 websocket
            console.log('连接已关闭...')
          }
          // 组件销毁时调用，中断websocket链接
          this.over = () => {
            ws.close()
          }
        } else {
          this.$KalixMessage.info('您当前使用的浏览器不支持WebSocket，无法接收服务器消息！')
        }
      },
      // 获取快捷按钮对应的数据字典
      _getDict(_id) {
        const DictURL = `/camel/rest/${_id}/dicts`
        const DictKey = `${_id.toUpperCase()}-DICT-KEY`
        if (!this.$KalixCatch.get(DictKey)) {
          const data = {
            page: 1,
            start: 0,
            limit: 200,
            sort: '[{\'property\': \'value\', \'direction\': \'ASC\'}]'
          }
          this.axios.get(DictURL, {
            params: data
          }).then(response => {
            if (response.data) {
              this.$KalixCatch.save(DictKey, JSON.stringify(response.data.data))
              console.log(`dict cached under key ${DictKey}`, response.data)
            }
          })
        }
      },
      _chkShortcutBtn(_itemId) {
        let items = this.$store.state.menuList.filter(item => {
          return item.id === _itemId
        })
        if (items.length > 0) {
          this._getDict(_itemId)
          return true
        }
        return false
      },
      // 判断是否显示快捷按钮
      _setTopBtns() {
        // 是否显示 消息 按钮
        this.isShowMessage = this._chkShortcutBtn('common')
        this.isReceiveMsg = this.isShowMessage

        // 是否显示 待办工作 按钮
        this.isFlowCommand = this._chkShortcutBtn('oa')

        // 建立websocket连接，接收服务器消息
        if (this.isReceiveMsg) {
          try {
            this.websocket()
          } catch (e) {
            console.error(e)
          }
        }
      }
    }
  }
</script>
